package com.zust.ysc012.servlet;

import com.zust.ysc012.entity.Table;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.zust.ysc012.dao.PublicDao.search_sql;
import static com.zust.ysc012.service.UploadedService.getAllTable2;

/**
 * @Description
 * @Author Mato
 * @Date 05/07/2021 13:30
 */
@WebServlet(urlPatterns = "/searchServlet")
public class SearchServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Table> tables = new ArrayList<>();
            List<Table> answerTables = new ArrayList<>();
            tables = getAllTable2();
            String search = req.getParameter("search");
            List answer = search_sql(search);
            for (int i = 0; i < answer.size(); i++) {
                for (int k = 0; k < tables.size(); k++) {
                    if((int) answer.get(i) == tables.get(k).getProject_number()) {
                        answerTables.add(tables.get(k));
                    }
                }
            }
            req.setAttribute("answer", answerTables);
            req.getRequestDispatcher("/WEB-INF/research.jsp").forward(req,resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
